﻿using System;
using System.Text;
using System.Text.RegularExpressions;

using LeanEngine.Extensions;
using LeanEngine.Exception;

namespace LeanEngine.Validation
{
    /// <summary>
    /// Attribute for validate values based on regular expression patterns when are not an empty string.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public sealed class IsEmptyOrMatchPatternAttribute : ValidationAttribute
    {
        #region Constructor Members

        /// <summary>
        /// Initialize a new instance of LeanEngine.Validation.IsEmptyOrMatchPatternAttribute class with a regular expression 
        /// pattern and an error message obtained from a resource file.
        /// </summary>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <param name="resourceType">The System.Type of the resource manager that holds the error message.</param>
        /// <param name="errorKey">The key error message contained in the resource.</param>
        /// <param name="pattern">The regular expression pattern</param>
        public IsEmptyOrMatchPatternAttribute(string pattern, Type resourceType, string errorKey)
            : base(resourceType, errorKey)
        {
            if (pattern.IsNullOrEmpty()) throw new ArgumentNullException("pattern");
            this.Pattern = pattern;
        }

        /// <summary>
        /// Initialize a new instance of LeanEngine.Validation.IsEmptyOrMatchPatternAttribute class with a regular expression 
        /// pattern and an specific error message.
        /// </summary>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <param name="pattern">The regular expression pattern</param>
        /// <param name="errorMessage">The error message displayed for non valid values.</param>
        public IsEmptyOrMatchPatternAttribute(string pattern, string errorMessage)
            : base(errorMessage)
        {
            if (pattern.IsNullOrEmpty()) throw new ArgumentNullException("pattern");
            this.Pattern = pattern;
        }

        #endregion

        #region PropertyInfo Members

        /// <summary>
        /// Gets the regular expression pattern that the value must match.
        /// </summary>
        public string Pattern
        {
            get;
            private set;
        }

        #endregion

        #region ValidationAttribute Members

        /// <summary>
        /// Validates the value according to the validation rule and throws an exception in case of validation failure.
        /// </summary>
        /// <exception cref="LeanEngine.Exception.BusinessException"></exception>
        /// <param name="value">The value to be validated.</param>
        public override bool Validate(object value)
        {
            if (value.IsNotNull())
            {
                var stringValue = value.ToString();
                if (stringValue.IsNotNullOrEmpty() &&
                    !Regex.IsMatch(stringValue, this.Pattern))
                {
                    throw new BusinessException(this.ErrorMessage);
                }
            }

            return true;
        }

        /// <summary>
        /// Validates the value according to the validation rule to the container and adds exception error in case of validation failure.
        /// </summary>
        /// <param name="value">The value to be validated.</param>
        /// <param name="errorMessageContainer">The container for all the error messages.</param>
        public override void Validate(object value, StringBuilder errorMessageContainer)
        {
            if (value.IsNotNull())
            {
                var stringValue = value.ToString();
                if (stringValue.IsNotNullOrEmpty() &&
                    !Regex.IsMatch(stringValue, this.Pattern))
                {
                    errorMessageContainer.Append(this.ErrorMessage);
                    errorMessageContainer.Append(Environment.NewLine);
                }
            }
        }

        #endregion
    }
}
